package net.spider.tasks.sankaku;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.cl.utils.FileUtil;
import net.cl.utils.SystemUtil;
import net.spider.dao.SankakuDao;
import net.spider.entity.ContentEntity;

public class DownloadTask extends Thread {

	private static final Log log = LogFactory.getLog(DownloadTask.class);

	public void run() {
		log.info("sankaku.DownloadTask started");
		while (true) {
			if (AnalyzeTask.QUEUE.isEmpty()) {
				if (isEnd())
					break;
				else {
					try {
						Thread.sleep(1000);
						log.info("DownloadTask sleep.");
					} catch (InterruptedException e) {
					}
					continue;
				}
			}
			try {
				ContentEntity entity = AnalyzeTask.QUEUE.take();
				log.info(entity.getFolder());
				StringBuilder sb = new StringBuilder();
				sb.append(entity.getUrl());
				sb.append(SystemUtil.getLineSeparator());
				sb.append(entity.getTitle());
				FileUtil.write(entity.getFolder() + "/" + entity.getId() + ".txt", sb.toString());
				String[] args = new String[] { "wget", "-i", entity.getFolder() + "/links.txt", "-P",
						entity.getFolder(), "-q", "-N" };
				exec(args);
				SankakuDao.insert(entity.getId(), entity.getUrl());
			} catch (Exception e) {
				log.error(e);
			}
		}
		log.info("sankaku.DownloadTask end");
	}

	public void exec(String[] args) {
		Process p = null;
		try {
			Runtime r = Runtime.getRuntime();
			p = r.exec(args);
			p.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			p.destroy();
		}
	}

	public boolean isEnd() {
		return AnalyzeTask.END;
	}

}
